import torch
import torch.nn as nn

X = torch.tensor([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]).view(-1, 1)
y = torch.tensor([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0]).view(-1, 1)

class MultiLayerPerceptron(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(1, 64)
        self.fc2 = nn.Linear(64, 1)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = MultiLayerPerceptron()
print("已经创建模型：", model)

loss_fnc = nn.MSELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for epoch in range(500):
    y_pred = model.forward(X)
    loss = loss_fnc(y_pred, y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (epoch + 1) % 50 == 0:
        print(f'Epoch [{epoch + 1}/500], Loss: {loss.item():.4f}')

with torch.no_grad():
    x_test = torch.tensor([10.0])
    y_test = model.forward(x_test.unsqueeze(0))
    print(f'测试输入x: {x_test.item()}')
    print(f'测试输出y: {y_test.item()}')